<template>
  <div class="tag-container">
    <div class="tag-wrapper">

      <div class="Tag-div" v-for="items in Tags">
        <!--      这一层循环用来确定放在哪一个标签框架中-->
        <div style="padding-bottom: 10px">
          <el-icon style="float: right" @click="TransItems(items)">
            <More />
          </el-icon>
        </div>
        <!--把某个块传到抽屉-->
        <ul class="TAG">
          <li v-for="item in items.tags">
            <!--      这一层循环用来确定放在此框架中的内容 -->
            <a :href="item['tag_URL']" target="_blank">{{ item['tag_Name'] }}</a>
          </li>
        </ul>

      </div>

    </div>
  </div>


  <div>
    <HomeDrawer :TagValue="TransValue" v-model="drawer"></HomeDrawer>
  </div>
</template>

<script setup lang="ts">
import { getDefaultTagFromServer, getUserTagFromServer } from '../api/get';

import { onMounted, ref } from 'vue';
import { checkUserLogin, storage } from '../utils';
import { More } from "@element-plus/icons-vue";
import HomeDrawer from "./HomeDrawer.vue";

const drawer = ref(false)

const Tags = ref<any>()

let TransValue:any;

// <!-- 标签 -->
// <!-- 判断是否登录
//         1.未登录 如果本地有数据则加载本地数据  否则直接加载本地默认标签
//         2.登录  查找相应用户数据 然后保存在本地中
// -->
async function initTag(index?:any) {
  const isLoggedIn = await checkUserLogin()
  if (isLoggedIn) {
    const Tagdata = await getUserTagFromServer();
    const TagList = Tagdata.reduce((result: any, item: any) => {
      const existingItem = result.find((x: any) => x.block_name === item.block_name);
      if (existingItem) {
        existingItem.tags.push(...item.tags);
      } else {
        result.push(item);
      }
      return result;
    }, [
      {
        block_name: '',
        tags: [
          {
            tag_Name: String,
            tag_URL: String,
            tag_id:Number
          },
        ]
      }
    ]);
    TagList.splice(0, 1)
    Tags.value = TagList

  } else {
    const localTagData = storage.get("Tags");
    if (localTagData) {
      Tags.value = localTagData._rawValue
    } else {
      try {
        const localTagData = await getDefaultTagFromServer()
        Tags.value = localTagData
        saveToLocalTag(Tags);
      } catch (err) {
        console.log(err)
      }
    }

  }
}

onMounted(() => {
  initTag()
})


function saveToLocalTag(Tags: any) {
  storage.set("Tags", Tags)
}
function TransItems(items: any){
  drawer.value=true
  console.log("transItems")
  console.log(items)
  TransValue=items
}



</script>

<style>
@import "../style/Tag.css";
</style>
